package com.atguigu.servlet;

import com.atguigu.utils.JDBCUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 基类servlet 将方法使用反射调用
 * @author dl
 * @create 2020-04-21-21:58
 */
public class BaseServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		this.doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// 解决 post 乱码 // test
		req.setCharacterEncoding("utf-8");
		resp.setHeader("Content-Type", "text/html;charset=UTF-8");
		String method = req.getParameter("method");
		try {
			Method reflectMethod = this.getClass().getDeclaredMethod(method, HttpServletRequest.class, HttpServletResponse.class);
			System.out.println(this.getClass().getName());
			// open visit access
			reflectMethod.setAccessible(true);
			reflectMethod.invoke(this,req,resp);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	/** 销毁数据库连接池 */
	@Override
	public void destroy() {
		JDBCUtils.destroy();
		super.destroy();
	}
}
